var tools = {}
import Config from '@/config.js';

/** 快速缓存数据，优先解析json处理 。
	读取：var val=cache(key); 保存：var res=this.$func.cache(key,val)
 * @param {Object} keystr
 * @param {Object} valstr
 */
tools.cache=function(keystr,valstr){
	if(valstr==undefined){
		var str=uni.getStorageSync(keystr);
		//str=Crypto.decrypt(str); 
		try{
			str=JSON.parse(str);
			return str;
		}catch(e){
			return  str;
		}
	}else{
		if(typeof(valstr)!='string'){
			valstr=JSON.stringify(valstr);
		}
		//let cry = Crypto.encrypt(valstr)
		uni.setStorageSync(keystr,valstr);
		return true;
	}
	
}
/**
 * 给二维数组（列表增加一个属性），例如给商品列表增加一个checked属性做选中标志
 * @param {Object} list  列表
 * @param {Object} key   属性
 * @param {Object} val   值
 */
tools.listAssign=function(list,key,val){
	list.forEach(function(item){
		Object.assign(item,{key:val});
	})
	return list;
}
/**
 * 当前时间戳
 */
tools.timestamp_now=function(){
	return Date.parse(new Date())/1000;
}  
/** 通过秒级时间戳返回指定格式时间
（0返回完整时间,1返回日期，2返回时间，3返回每个节点数组,4返回时分）
 * @param {Object} time
 * @param {Object} type
 * @param {Object} wrong
 */
tools.datetime = function (time, type ) {
  type = type || 0; 
  var timestamp = parseFloat(time) > 0 ? time * 1000 : 0;
  var date = new Date(timestamp);

  var month = date.getMonth() + 1;
  var day = date.getDate(), hour = date.getHours(), min = date.getMinutes(), sec = date.getSeconds();
  var ret = {
    "y": date.getFullYear(),
    "m": month,
    "d": day,
    h: hour,
    "i": hour,
    's': sec,
    w: date.getDay(),
    "year": date.getFullYear()
  }
  if (month >= 1 && month <= 9) {
    month = "0" + month;
  }
  if (day >= 0 && day <= 9) {
    day = "0" + day;
  }
  if (hour >= 0 && hour <= 9) {
    hour = "0" + hour;
  }
  if (min >= 0 && min <= 9) {
    min = "0" + min;
  }
  if (sec >= 0 && sec <= 9) {
    sec = "0" + sec;
  }
  if (type == 3) {
    //简写ymdisw小于10不带0,星期不转化汉字
    ret.month = month;
    ret.day = day;
    ret.hour = hour;
    ret.second = sec;
    var weekday = ["日", "一", "二", "三", "四", "五", "六"];
    ret.weekday = weekday[date.getDay()];
    ret.date = date.getFullYear() + "-" + month + "-" + day;
    ret.time = hour + ":" + min + ":" + sec;
  } else if (type == 4) {
    ret = hour + ":" + min;
  } else if (type == 5) {
    ret = date.getFullYear() + "-" + month + "-" + day + " " + hour + ":" + min;
  } else if (type == 2) {
    ret = hour + ":" + min + ":" + sec;
  } else if (type == 1) {
    ret = date.getFullYear() + "-" + month + "-" + day;
  } else {
    ret = date.getFullYear() + "-" + month + "-" + day + " " + hour + ":" + min + ":" + sec
  }
  return ret;
}
/** 通过时间返回秒级时间戳
 * @param {Object} str 日期或完整时间 ，Y-m-d 或 Y-m-d H:i:s
 */
tools.strtotime = function (str) {
  if (str.indexOf(":") < 0) {
    var date = Date.parse(new Date(str.replace(/-/, "/"))) / 1000;
    return date;
  } else {
    var arr1 = str.split(" ");
    var sdate = arr1[0].split('-');
    var date = Date.parse(new Date(sdate[0], sdate[1] - 1, sdate[2])) / 1000;
    return date;
  }
}
tools.initPage = function (page,objData) { 
	
	var initData= {
		 page:0,per_page:20,total:20,nomore:0
	}
	if(typeof(objData)!='undefined'){
		var obj={
			page:0,per_page:20,total:0,nomore:0
		};
		if(typeof(objData.current_page)!='undefined'){
			obj.page=objData.current_page;
			obj.total=objData.total;
			obj.per_page=objData.per_page;
			if(Math.ceil(objData.total/objData.per_page)<=parseInt(objData.page)){
				  obj.nomore=1; 
			}
		} 
		page._data = Object.assign(page._data,{paginate: obj})
	}else{ 
		page._data = Object.assign(page._data,{paginate:initData})
		if(typeof(page._data.paginate)!='undefined'){
			page._data.paginate=initData;
			return initData;
		}
		 
		
	}
	
   return page._data.paginate;
}
tools.nextPage = function (page) {
  var pag = page._data.paginate;
  let total_page=Math.ceil(pag.total/pag.per_page);
  
  if(total_page>parseInt(pag.page)){
	  pag.page++;
	  page._data.paginate=pag;
	  return pag;
  }else {
    return false;
  }
   
} 
//加法函数，用来得到精确的加法结果  
tools.jia = function (arg1, arg2) {
  var r1, r2, m;
  try { r1 = arg1.toString().split(".")[1].length } catch (e) { r1 = 0 }
  try { r2 = arg2.toString().split(".")[1].length } catch (e) { r2 = 0 }
  m = Math.pow(10, Math.max(r1, r2));
  return (arg1 * m + arg2 * m) / m;

}
//乘法函数，用来得到精确的乘法结果    
tools.cheng = function (arg1, arg2) {
  var m = 0, s1 = arg1.toString(), s2 = arg2.toString();
  try { m += s1.split(".")[1].length } catch (e) { }
  try { m += s2.split(".")[1].length } catch (e) { }
  return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);
}
//除法函数，用来得到精确的加法结果 
// a/b=chu(a,b)   
tools.chu = function (arg1, arg2) {
  var t1 = 0, t2 = 0, r1, r2;
  try { t1 = arg1.toString().split(".")[1].length } catch (e) { }
  try { t2 = arg2.toString().split(".")[1].length } catch (e) { }
  r1 = Number(arg1.toString().replace(".", ""))
  r2 = Number(arg2.toString().replace(".", ""))
  return (r1 / r2) * Math.pow(10, t2 - t1);

}
//减法函数   a-b=jian(a,b)
tools.jian = function (arg2, arg1) {
  var r1, r2, m, n;
  try { r1 = arg1.toString().split(".")[1].length } catch (e) { r1 = 0 }
  try { r2 = arg2.toString().split(".")[1].length } catch (e) { r2 = 0 }
  m = Math.pow(10, Math.max(r1, r2));
  //lastmodifybydeeka  
  //动态控制精度长度  
  n = (r1 >= r2) ? r1 : r2;
  return ((arg2 * m - arg1 * m) / m).toFixed(n);
}
/** 随机整数
 * @param {Object} min
 * @param {Object} max
 */
tools.rand = function (min, max) {
  return parseInt(Math.random() * (max - min + 1) + min, 10)
}
/** 随机字符串
 * @param {Object} len 长度
 * @param {Object} fuhao 是否包含特殊符号
 */
tools.randChar = function (len, fuhao) {
  var arr = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789,.?:[]!@#$%^&*()_+=-";
  var max = 61;
  if (typeof (fuhao) != "undefined") max = 82;
  len = (len == undefined || !parseInt(len)) ? 10 : len;
  var str = "";
  for (var i = 0; i < len; i++) {
    str += arr[this.rand(0, max)];
  }
  return str;
} 
//正则验证
tools.validateParam=function (arr){
	for (var i in arr ){
		if(arr[i].length==4){
			var ret=this.check(arr[i][0],arr[i][1],arr[i][2],arr[i][3]);
		}else{
			var ret=this.check(arr[i][0],arr[i][1],arr[i][2]);
		}
		
		if(ret!==true){
			return ret;
		}
	}
	return true;
}
tools.check=function(name,str,type,extra){
	if(typeof(str)=='undefined'){
		return "无法读取到 "+name
	}
    var ret=false; 
	var msg='';
    switch(type){
        case "username":
            var nameCheck=/^[A-Za-z0-9]*$/;
            if(nameCheck.test(str)&&(str.length>3&&str.length<21)){
                ret=true;
            } 
            break;
        case "chinese":
            var pattern=/^[\u4e00-\u9fa5]+$/;
            if(pattern.test(str)){
                ret = true;
            }
            ret = false;
            break;
        case "date":
            var str=str;
            var DateCheck= /^(\d+)\-(\d+)\-(\d+)$/;
            //正则表达式 匹配出生日期(简单匹配)     
            if (DateCheck.test(str)){
                str.match(DateCheck);
                //设置时间范围年1976-3000 时0-23 分0-59 秒0-59
                if(RegExp.$1<=3000&&RegExp.$1>=1970){
                        var iyear=(RegExp.$1)%4;
                        //如果月份为小则 日1-30 如果月份为大1-31 如果为润2月 1-29 平2月 1-28
                        if((RegExp.$2==4||RegExp.$2==5||RegExp.$2==9||RegExp.$2==11)&&(RegExp.$3>=1&&RegExp.$3<=30)){
                            ret = true;
                        }else if((RegExp.$2==1||RegExp.$2==3||RegExp.$2==5||RegExp.$2==7||RegExp.$2==8||RegExp.$2==10||RegExp.$2==12)&&(RegExp.$3>=1&&RegExp.$3<=31)){
                            ret = true;
                        }else if(RegExp.$2==2&&iyear==0&&RegExp.$3>=1&&RegExp.$3<=29){
                            ret = true;
                        }else if(RegExp.$2==2&&iyear!=0&&RegExp.$3>=1&&RegExp.$3<=28){
                            ret = true;
                        }
                        else{
                            ret = false;
                        }
                    }else{
                        ret = false;
                    }
            }else{
                ret = false;
            }
            break;
        case "datetime": 
            var DateCheck= /^(\d+)\-(\d+)\-(\d+)\ (\d+)\:(\d+)\:(\d+)$/;
            //正则表达式 匹配出生日期(简单匹配)     
            if (DateCheck.test(str)){
                str.match(DateCheck);
                //设置时间范围年1976-3000 时0-23 分0-59 秒0-59
                if(RegExp.$1<=3000&&RegExp.$1>=1970
                    &&RegExp.$4<=23&&RegExp.$4>=0
                    &&RegExp.$5<=59&&RegExp.$5>=0
                    &&RegExp.$6<=59&&RegExp.$6>=0){
                        var iyear=(RegExp.$1)%4;
                        //如果月份为小则 日1-30 如果月份为大1-31 如果为润2月 1-29 平2月 1-28
                        if((RegExp.$2==4||RegExp.$2==5||RegExp.$2==9||RegExp.$2==11)&&(RegExp.$3>=1&&RegExp.$3<=30)){
                            ret = true;
                        }else if((RegExp.$2==1||RegExp.$2==3||RegExp.$2==5||RegExp.$2==7||RegExp.$2==8||RegExp.$2==10||RegExp.$2==12)&&(RegExp.$3>=1&&RegExp.$3<=31)){
                            ret = true;
                        }else if(RegExp.$2==2&&iyear==0&&RegExp.$3>=1&&RegExp.$3<=29){
                            ret = true;
                        }else if(RegExp.$2==2&&iyear!=0&&RegExp.$3>=1&&RegExp.$3<=28){
                            ret = true;
                        }
                        else{
                            ret = false;
                        }
                    }else{
                        ret = false;
                    }
            }else{
                ret = false;
            }
            break;
        case "mac":
            //获取验证Mac  
            var MacCheck = /^[a-fA-F\d]{2}\:[a-fA-F\d]{2}\:[a-fA-F\d]{2}\:[a-fA-F\d]{2}\:[a-fA-F\d]{2}\:[a-fA-F\d]{2}$/;  
            if (MacCheck.test(str)){
                ret = true;
            }else{
                ret = false;
            }
            break;
        case "float":
            //获取验证float 
            var FloatCheck=/^(\d+)(\.?)\d{0,3}$/;
            if (FloatCheck.test(str)){
                var FloatCheck1=/^(\d+)\.$/;
                if(FloatCheck1.test(str))
                {
                    ret = false;
                }else{
                    ret = true;
                }
            }else{
                ret = false;
            }
            break;
        case "int": 
            //正则表达式
            var IntCheck=/^(\d+)$/;
            if (IntCheck.test(str)){
                ret = true;
            }else{
                ret = false;
            }
			var arr=extra.split(",");
			if(typeof(arr[0])!="undefined"&&typeof(arr[1])!="undefined"){
				if(parseInt(str)>=parseInt(arr[0])&&parseInt(str)<=parseInt(arr[1])){
					ret=true
				}else{
					ret=false;
				}
			}else if(typeof(arr[0])!="undefined"){
				if(parseInt(str)>=parseInt(arr[0])){
					ret=true
				} else{
					ret=false
				}
			} 
            break;
        case "mobile":
            var isMob=/^1[3456789]\d{9}$/;
            if(isMob.test(str)){
                ret = true;
            }
            else{
                ret = false;
            } 
            break;
        case "phone":
            //手机号或者座机
            var isPhone = /^([0-9]{3,4}-)?[0-9]{7,8}$/;
            var isMob=/^1[3456789]\d{9}$/;
            if(isMob.test(str)||isPhone.test(str)){
                ret = true;
            }
            else{
                ret = false;
            } 
            break;
        case "email":
            //邮箱
            var EmailCheck=/^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/;
            if (EmailCheck.test(str)){
                ret = true;
            }else{
                ret = false;
            }
            break;
        case "idcard":
			     // 加权因子
			var idcode=str;
		   var weight_factor = [7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2];
		   // 校验码
		   var check_code = ['1', '0', 'X' , '9', '8', '7', '6', '5', '4', '3', '2'];
	   
		   var code = idcode + "";
		   var last = idcode[17];//最后一位
	   
		   var seventeen = code.substring(0,17);
	   
		   // ISO 7064:1983.MOD 11-2
		   // 判断最后一位校验码是否正确
		   var arr = seventeen.split("");
		   var len = arr.length;
		   var num = 0;
		   for(var i = 0; i < len; i++){
			   num = num + arr[i] * weight_factor[i];
		   }
		   
		   // 获取余数
		   var resisue = num%11;
		   var last_no = check_code[resisue];
	   
		   // 格式的正则
		   // 正则思路
		   /*
		   第一位不可能是0
		   第二位到第六位可以是0-9
		   第七位到第十位是年份，所以七八位为19或者20
		   十一位和十二位是月份，这两位是01-12之间的数值
		   十三位和十四位是日期，是从01-31之间的数值
		   十五，十六，十七都是数字0-9
		   十八位可能是数字0-9，也可能是X
		   */
		   var idcard_patter = /^[1-9][0-9]{5}([1][9][0-9]{2}|[2][0][0|1][0-9])([0][1-9]|[1][0|1|2])([0][1-9]|[1|2][0-9]|[3][0|1])[0-9]{3}([0-9]|[X])$/;
	   
		   // 判断格式是否正确
		   var format = idcard_patter.test(idcode);
		 
		   // 返回验证结果，校验码和格式同时正确才算是合法的身份证号码
		    ret=( last === last_no && format)? true : false; 
	  
            break;
        case "ip"://检验IPv4地址 
            var ipCheck = /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/;  
            if (ipCheck.test(str)){
                //判断IP是否在有效范围内
                str.match(ipCheck);
                if(RegExp.$1<=255&&RegExp.$1>=0
                    &&RegExp.$2<=255&&RegExp.$2>=0
                    &&RegExp.$3<=255&&RegExp.$3>=0
                    &&RegExp.$4<=255&&RegExp.$4>=0){  
                    ret = true; 
                }else{
                    ret = false;
                }  
            }else{
                 ret = false; 
            }
            break; 
		case 'require':
		 
			if(str.trim().length>0){
				ret = true;
			}
			msg=name+"不能为空";
			break;
		case 'length':
			if(typeof(extra)=="undefined")break;
			var arr=extra.split(",");
			if(typeof(arr[0])!="undefined"&&typeof(arr[1])!="undefined"){
				if(str.trim().length>=parseInt(arr[0])&&str.trim().length<=parseInt(arr[1])){
					ret=true
				}
				msg=name+" 长度:"+arr[0]+" 到 "+arr[1] +"位";
			}else if(typeof(arr[0])!="undefined"){
				if(str.trim().length>=parseInt(arr[0])){
					ret=true
				}
				msg=name+" 长度至少"+arr[0]+"位";
			} 
			
			
        default:
            break;
    }
    if(ret!==true){
		if(msg==""){
			msg=name+"格式不正确"
		}
		return msg;
	}else{
		return true;
	}
}

module.exports = tools